<script lang="ts" setup>
import type { Select } from '#/api';

import { onMounted, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { useRefresh } from '@vben/hooks';

import { ElOption, ElPagination, ElSelect } from 'element-plus';

import { listSelectTenant } from '#/api/platform/systenant';
import { $t } from '#/locales';
import { useXTenantStore } from '#/store';

const emit = defineEmits(['success']);

const { refresh } = useRefresh();

const xtenantStore = useXTenantStore();
const xTenantId = ref();
const xTenantName = ref();

// 常量定义
const INITIAL_TENANT: Select = {
  id: 'all',
  label: '全部租户数据',
};

// 响应式数据
const tenant_list = ref<Select[]>([]);
const tenant_total = ref(0);
const pageParam = ref({
  pageNum: 1,
  pageSize: 5,
});

// 模态框逻辑
const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    modalApi.lock();
    try {
      xtenantStore.setXTenantId(xTenantId.value);
      xtenantStore.setXTenantName(xTenantName.value);
      refresh();

      modalApi.close();
      emit('success');
    } finally {
      modalApi.lock(false);
    }
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      return;
    }
    modalApi.setState({
      title: $t('tenant.switchTenant'),
    });
    if (tenant_total.value === 0) {
      selectTenant();
    }
  },
});

/**
 * 获取租户列表
 */
async function selectTenant(tenantName?: string) {
  try {
    const res = await listSelectTenant({
      ...pageParam.value,
      tenantName,
    });

    tenant_list.value = [INITIAL_TENANT, ...res.rows];
    tenant_total.value = res.total;
  } catch (error) {
    console.error('获取租户列表失败:', error);
  }
}

/**
 * 远程搜索方法
 */
function remoteMethod(tenantName: string) {
  if (tenantName.trim()) {
    setTimeout(() => {
      pageParam.value.pageNum = 1; // 搜索时重置页码
      selectTenant(tenantName);
    }, 200);
  }
}

/** 选择框回显 */
onMounted(() => {
  xTenantId.value = xtenantStore.xtenantId;
});
</script>

<template>
  <Modal class="max-h-[300px] max-w-[300px]">
    <ElSelect
      v-model="xTenantId"
      :placeholder="$t('tenant.superTenant')"
      clearable
      filterable
      remote
      remote-show-suffix
      :remote-method="remoteMethod"
      @change="
        (id) => {
          xTenantId = id;
          xTenantName = tenant_list.find((item) => item.id === id)?.label;
        }
      "
    >
      <ElOption
        v-for="item in tenant_list"
        :key="item.id"
        :label="item.label"
        :value="item.id"
      />

      <template #footer>
        <ElPagination
          size="small"
          layout="total, prev, next"
          :total="tenant_total"
          :page-size="pageParam.pageSize"
          :current-page="pageParam.pageNum"
          @current-change="
            (val: number) => {
              pageParam.pageNum = val;
              selectTenant();
            }
          "
          @size-change="
            (val: number) => {
              pageParam.pageSize = val;
              selectTenant();
            }
          "
        />
      </template>
    </ElSelect>
  </Modal>
</template>
